<template>
  <div>
    <n-space style="margin-bottom:12px">
      <n-input-number v-model:value="taskId" placeholder="任务ID" style="width:120px" />
      <n-button type="primary" @click="load" :loading="loading">查看</n-button>
      <n-button type="error" ghost @click="clear" :disabled="items.length===0">清空</n-button>
      <n-text depth="3">输入任务ID查看死信队列</n-text>
    </n-space>

    <n-card size="small" title="死信队列">
      <template v-if="items.length === 0">
        <n-empty description="暂无死信数据" />
      </template>
      <template v-else>
        <n-space vertical>
          <div v-for="(it, idx) in items" :key="idx" class="dlq-item">
            <n-card size="small" :title="`消息 #${idx + 1}`">
              <n-tabs type="line">
                <n-tab-pane name="text" tab="文本">
                  <n-code :code="decode(it)" language="text" />
                </n-tab-pane>
                <n-tab-pane name="hex" tab="十六进制">
                  <n-code :code="toHex(it)" language="text" />
                </n-tab-pane>
                <n-tab-pane name="base64" tab="Base64">
                  <n-code :code="it" language="text" />
                </n-tab-pane>
              </n-tabs>
            </n-card>
          </div>
        </n-space>
      </template>
    </n-card>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'
import { NButton, NInputNumber, NSpace, NCard, NCode, NEmpty, NText, NTabs, NTabPane, useMessage } from 'naive-ui'

const message = useMessage()
const taskId = ref<number | null>(null)
const items = ref<string[]>([])
const loading = ref(false)

function decode(b64: string) {
  try {
    return atob(b64)
  } catch {
    return b64
  }
}

function toHex(b64: string) {
  try {
    const binary = atob(b64)
    return Array.from(binary)
      .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
      .join(' ')
  } catch {
    return b64
  }
}

async function load() {
  if (taskId.value == null) {
    message.warning('请输入任务ID')
    return
  }

  loading.value = true
  try {
    const { data } = await axios.get(`/api/dlq/${taskId.value}`)
    items.value = data
    message.success(`加载了 ${data.length} 条死信`)
  } catch (e) {
    message.error('加载失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

async function clear() {
  if (taskId.value == null) return

  try {
    await axios.delete(`/api/dlq/${taskId.value}`)
    await load()
    message.success('已清空')
  } catch (e) {
    message.error('清空失败')
  }
}
</script>
<style scoped>
.dlq-item {
  margin-bottom: 12px;
}
</style>

